<template>
  <div class="content">
    <div class="imgs">
      <el-image class="img" :src="url"></el-image>
      <el-upload
        class="imgUpload"
        action="abc"
        list-type="text"
        accept="image/*"
        :limit="1"
        :file-list="imgFileList"
        :auto-upload="false"
        :on-change="handleFileChange"
        :show-file-list="false"
      >
        <el-button class="buttons" size="normal" plain type="primary"
          >替换</el-button
        >
        <div class="el-upload__tip" slot="tip">
          图片大小不超过2Mb，推荐长宽比5:3
        </div>
      </el-upload>
    </div>
  </div>
</template>
<script>
import CompressImg from "../utils/compressImg.js";
import Config from "../config";
import loading from "../../loading";
export default {
  components: {},
  data() {
    return {
      imgFileList: [],
      blobImg: "",
      url: "",
    };
  },
  created() {
    this.getBgUrl();
  },
  mounted() {},
  methods: {
    async getBgUrl() {
      if (window.sessionStorage.getItem("bgUrl") != null) {
        this.url = window.sessionStorage.getItem("bgUrl");
        console.log("已从本地缓存获取背景图片地址", this.url);
        this.url = this.url.split("'")[1];
      } else {
        const res = await this.$axios.get(`${this.HOST}/config/api/background`);
        console.log("获取背景图片成功", res.data.data);
        let bgUrl = Config.picPrefixUrl + res.data.data.background;
        this.url = "url('" + bgUrl + "')";
        window.sessionStorage.setItem("bgUrl", this.url);
        this.url = this.url.split("'")[1];
      }
    },
    /**
     * 上传轮播图
     */
    async submitUploadBgImg() {
      let formData = new FormData();
      formData.append("file", this.blobImg);
      const _loading = loading("上传中，请稍等...");
      const config = {
        onUploadProgress: (progressEvent) => {
          this.progressPercent = Number(
            ((progressEvent.loaded / progressEvent.total) * 100).toFixed(0)
          );
          _loading.setText("上传中，进度：" + this.progressPercent + "%"); //更新dialog进度，优化体验
        },
        headers: {
          "Content-Type": "multipart/form-data",
        },
      };
      try {
        const res = await this.$axios.post(
          `${this.HOST}/config/api/uploadBackGroup`,
          formData,
          config
        );
        if (res.data.meta.code == 200) {
          this.$message({
            message: "添加成功！",
            type: "success",
            showClose: true,
          });
          this.imgFileList.pop();
          window.sessionStorage.removeItem("bgUrl");
          this.$router.go(0);
        }
      } finally {
        this.imgFileList.pop();
        _loading.close();
      }
    },
    handleFileChange(file) {
      this.uploadImg(file.raw);
    },
    async uploadImg(file) {
      let img = await CompressImg(file);
      console.log("img", img);
      this.blobImg = img.file;
      this.submitUploadBgImg(file);
    },
  },
};
</script>

<style lang="less" scoped>
.content {
  padding-left: 30px;
  padding-right: 30px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;

  .imgs {
    margin-bottom: 10px;
    width: 900px;
    text-align: center;

    .img {
      box-shadow: 0px 0px 10px gray;
      border-radius: 2px;
      width: 100%;
      height: auto; // 5:3
      margin-bottom: 10px;
    }
  }
}
</style>